import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import requests
import json
from reqapi.api import BaseApi
from com.db.order_account_manager import OrderAccountManager

class PaymentConfirmApi(BaseApi):
    def execute(self, order_no, out_trade_no, wait_payment_data_no, payment_amount, 
               business_type="1", channel_id="100", pay_way=7, sub_bus_type="20000"):
        """
        确认支付订单API
        
        Args:
            order_no: 订单号
            out_trade_no: 外部交易号
            wait_payment_data_no: 等待支付数据号
            payment_amount: 支付金额
            business_type: 业务类型，默认"1"
            channel_id: 支付渠道ID，默认"100"（有品余额）
            pay_way: 支付方式，默认7
            sub_bus_type: 子业务类型，默认"20000"
            
        Returns:
            dict: 包含以下字段的字典：
                - payWay: 支付方式
                - payString: 支付字符串
                - payOrderNo: 支付订单号
                - totalAmount: 总金额
                - currency: 货币类型
                - tradeOrderNo: 交易订单号
                - needPay: 是否需要支付
        """
        url = f"{self.BASE_URL}/api/youpin/bff/payment/v1/pay/order/confirm"
        
        data = {
            "businessType": business_type,
            "channelId": channel_id,
            "extend": "{\"appInstall\":false}",
            "orderNo": order_no,
            "outTradeNo": out_trade_no,
            "payWay": pay_way,
            "paymentAmount": str(payment_amount),
            "subBusType": sub_bus_type,
            "waitPaymentDataNo": wait_payment_data_no,
            "Sessionid": self.device_id
        }
        headers = self.common_headers.copy()
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print(f"响应数据: {json.dumps(result, indent=2, ensure_ascii=False)}")
            if result.get('code') != 0:
                print(f"API返回错误: {result.get('msg', '未知错误')}")
                return None
            data = result.get('data', {})
            return {
                'payWay': data.get('payWay'),
                'payString': data.get('payString'),
                'payOrderNo': data.get('payOrderNo'),
                'totalAmount': data.get('totalAmount'),
                'currency': data.get('currency'),
                'tradeOrderNo': data.get('tradeOrderNo'),
                'needPay': data.get('needPay')
            }
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            return None


def main():
    """测试支付确认API"""
    try:
        # 使用实际的认证信息
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
            
        if not account:
            print("无法获取ID为1的账号")
            return
            
        device_id = account.get('device_id', '')
        auth_token = account.get('uu_token', '')
        uk = account.get('uk', '')
        
        # 创建API实例
        api = PaymentConfirmApi(
            device_token=device_id,  # 使用 device_id 作为 device_token
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 调用API
        result = api.execute(
            order_no="2025020210964679356",
            out_trade_no="202502022325764608",
            wait_payment_data_no="202502021678799221",
            payment_amount="0.07"
        )
        
        # 打印结果
        print("\n=== 支付确认API测试结果 ===")
        if result is None:
            print("支付确认失败，可能是登录信息失效或接口返回错误。")
        else:
            print(f"支付方式: {result['payWay']}")
            print(f"支付订单号: {result['payOrderNo']}")
            print(f"交易订单号: {result['tradeOrderNo']}")
            print(f"总金额: {result['totalAmount']} {result['currency']}")
            print(f"是否需要支付: {'是' if result['needPay'] else '否'}")
            if result['payString']:
                print(f"支付字符串: {result['payString']}")

    except Exception as e:
        print(f"测试失败: {str(e)}")


if __name__ == "__main__":
    main()
